import 'dart:convert';

import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:vape_xe/routes/app_pages.dart';
import 'package:vape_xe/services/services.dart';
import 'package:vape_xe/utils/utils.dart';
import 'package:vape_xe/values/values.dart';

class EarnController extends GetxController {
  /// 响应式成员变量
  final todayOrTotal = 1.obs;
  final rewardsList = [].obs;
  final earnData = <String, dynamic>{}.obs;
  final balance = .0.obs;
  final totalEarnings = .0.obs;

  /// 成员变量
  int pageSize = 20;
  int pageNumber = 1;
  final RefreshController refreshController = RefreshController(
    initialRefresh: false,
  );

  /// 事件
  void onRefresh() async {
    fetchNewsList(isRefresh: true).then((_) {
      refreshController.refreshCompleted(resetFooterState: true);
    }).catchError((e) {
      refreshController.refreshFailed();
    });
  }

  void onLoading() async {
    fetchNewsList().then((_) {
      if (rewardsList.isEmpty) {
        refreshController.loadNoData();
      } else {
        refreshController.loadComplete();
      }
    }).catchError((e) {
      Get.log('获取数据失败：$e');
      refreshController.loadFailed();
    });
  }

  void toggleTodayOrTotal(int value) {
    // 切换收益列表
    if (todayOrTotal.value == value) return;
    todayOrTotal.value = value;
    fetchNewsList(isRefresh: true);
  }

  Future<void> fetchNewsList({bool isRefresh = false}) async {
    var result = await Request().get('/userRewards/inviteCollectList', {
      'type': todayOrTotal.value,
      'pageSize': pageSize,
      'pageNumber': pageNumber,
    });

    if (isRefresh == true) {
      pageNumber = 1;
      rewardsList.clear();
    } else {
      pageNumber++;
    }
    rewardsList.addAll(result['result']);
  }

  /// 生命周期
  @override
  void onInit() {
    super.onInit();
    var earnDataOffline = StorageService.to.getString(STORAGE_EARN_INFO);
    if (earnDataOffline.isNotEmpty) {
      earnData.value = jsonDecode(earnDataOffline);
      balance.value = double.parse(earnData['money']?.toString() ?? '0');
      totalEarnings.value = double.parse(earnData['moneyTotal']?.toString() ?? '0');
    }
    ever(EventService.to.message, (message) async {
      if (message.startsWith('${EventService.EventLaunch}_${EventService.ModuleWithdrawList}')) {
        Get.toNamed(Routes.WITHDRAWLIST);
      }
    });
  }

  @override
  void onReady() async {
    super.onReady();
    await Request().get('/user/indexData').then((result) {
      earnData.value = result['result'];
      balance.value = double.parse(earnData['money']?.toString() ?? '0');
      totalEarnings.value = double.parse(earnData['moneyTotal']?.toString() ?? '0');
      StorageService.to.setString(STORAGE_EARN_INFO, jsonEncode(result['result']));
    });
    fetchNewsList(isRefresh: true);
  }
}
